// import Utils from "@/utils/utils";
import Request from "@/api/baseRequest.js";
import wx from 'weixin-js-sdk'
import { mapGetters } from 'vuex'

export const mixin_Share = {
    data() {
        return {
            time: "",
            banner: null,
            timer: null,
            jmUrl: '',
            token: '',
            code: '',
            urlParam: this.$route.query,
            activityId: null,
            userId: null,
            shareId: 0,
            baseurl: 'http://shanxihongdi.com',
            appid: 'wx5124771a6eb468fc',
            local: 'http://252o888o54.wicp.vip',
            activity: {}
        }
    },
    computed: {
        ...mapGetters([ // 使用辅助函数 mapGetters
            'getActivity', // 映射 this.getActivity为 this.$store.getters.getActivity
        ])
    },
    async created() {
        await this.urlToStorage();
        this.ActivityList();
    },
    methods: {
        urlToStorage() {
            this.urlParam = this.$route.query;
            if (!sessionStorage['id']) sessionStorage.setItem('id', this.urlParam.id);
            if (!sessionStorage['userId']) sessionStorage.setItem('userId', this.urlParam.userId);
            if (!sessionStorage['shareId']) sessionStorage.setItem('shareId', this.urlParam.shareId);
        },
        async ActivityList() {
            var self = this;
            let params = {
                id: self.activityId || self.GetParam(window.location.href, "id") || sessionStorage['id'],
                userId: self.userId || self.GetParam(window.location.href, "userId") || sessionStorage['userId'],
                shareId: self.shareId || self.GetParam(window.location.href, "shareId") || sessionStorage['shareId'],
            };
            const { code, activity } = await Request.getActivity(params);
            if ([200, "200", "OK", 0].includes(code)) {
                self.activity = activity;
                let { endDate, banner } = activity;
                self.changePayStatus(activity)
                self.banner = self.setStyle(self.baseurl + banner);
                await self.getActivityTime(endDate);
            }
        },
        HTMLDecode(str) {
            if (!str) return null;
            return str
                .replace(str ? /&(?!#?\w+;)/g : /&/g, '&amp;')
                .replace(/&lt;/g, "<")
                .replace(/&gt;/g, ">")
                .replace(/&quot;/g, "\"")
                .replace(/&#39;/g, "\"");
        },
        // dom加载背景图
        setStyle: (url) => ({
            backgroundImage: `url(${url})`,
            backgroundSize: "100% 100%",
            backgroundPosition: "center center",
            backgroundRepeat: "no-repeat"
        }),
        // 截取code
        GetParam(url, code) {
            url = url + "";
            let regstr = "/(\\?|\\&)" + code + "=([^\\&]+)/";
            let reg = eval(regstr);
            let result = url.match(reg);
            if (result && result[2]) {
                return !Number(result[2]) ? '' : Number(result[2]);
            }
        },
        timeDiff(start, end, h = 24, m = 60, s = 3600, ms = 1000) {
            // start: 创建时间/更新时间
            // end  : 当前时间/结束时间
            start = start ? new Date(start) : new Date();
            end = end ? new Date(Date.parse(end.replace(/-/g, '/'))) : new Date();
            var fl = o => Math.floor(o);
            var df = end - start;
            if (df <= 0) return {
                DD: '00',
                HH: '00',
                mm: '00',
                ss: '00'
            }
            var DD = fl(df / (h * s * ms)); //计算出小时数
            // if (DD < 31) return false;     //超过30天\第31天开始提示
            var v1 = df % (h * s * ms); //计算天数后剩余的毫秒数
            var HH = fl(v1 / (s * ms)); //计算相差分钟数
            var v2 = v1 % (s * ms); //计算小时数后剩余的毫秒数
            var mm = fl(v2 / (m * ms)); //计算相差秒数
            var v3 = v2 % (m * ms); //计算分钟数后剩余的毫秒数
            var ss = Math.round(v3 / ms);
            // return DD + '天' + HH + '时' + mm + '分钟' + ss + '秒'
            return {
                DD: DD,
                HH: HH,
                mm: mm,
                ss: ss
            }
        },
        getActivityTime(endTime) {
            let self = this;
            self.timer = setInterval(() => {
                self.time = this.timeDiff(null, endTime);
            }, 1000);
        },
        back() {
            if (window.history.length <= 1) {
                this.$router.push({ path: "/" });
                return false;
            } else {
                this.$router.go(-1);
            }
            //上面都没执行就说明卡在当前页不是最后一条， histroy记录数量大于1，又没有回退记录，只能返回首页，
            //如果上面都执行了 页面都跳走了，这个也就不用管了
            setTimeout(() => {
                this.$router.push({ path: "/" });
            }, 500);
        },
        wechatAuth: async (params) => await Request.wxAuth(params),
        getShareInfo() { //如果分享的内容会根据情况变化，那么这里可以传入分享标题及url
            let _this = this;
            var data = { //请求参数
                url: window.location.href.split("#")[0]
            }
            Request.getJsapiTicket(data) //这里我写了一个公用的接口请求js，这里正常axios请求就可以，只要拿到数据都可以
                .then(res => {
                    localStorage.setItem("jsapi_ticket", res.jsapiSignature);
                    if (![200, "200", "OK", 0].includes(res.code)) {
                        return false;
                    }
                    wx.config({
                        //...res.jsapiSignature,
                        ...{
                            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                            appId: res.jsapiSignature.appId, // 必填，公众号的唯一标识，填自己的！
                            timestamp: res.jsapiSignature.timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
                            nonceStr: res.jsapiSignature.nonceStr, // 必填，生成签名的随机串
                            signature: res.jsapiSignature.signature, // 必填，签名，见附录1
                            jsApiList: [
                                'updateTimelineShareData',
                                'updateAppMessageShareData',
                                'checkJsApi',
                                'getLocation',
                                'openLocation'
                            ]
                        }
                    })
                    wx.ready(function () {
                        //分享到朋友圈
                        wx.updateTimelineShareData({
                            desc: _this.getActivity.shareDesc,
                            title: _this.getActivity.shareTitle, // 分享时的标题
                            link: 'https://shanxihongdi.com/hd-api/app/wechatOauth/' + _this.getActivity.id + '?shareId=' + _this.getActivity.userId, // 分享时的链接
                            imgUrl: 'https://shanxihongdi.com/' + _this.getActivity.shareIcon,
                            success: function () {
                                console.log('分享朋友圈成功');
                                // this.$Alert({ title: "分享", message: '分享朋友圈成功' });
                            },
                            cancel: function () {
                                console.log('取消朋友圈分享');
                                // this.$Alert({ title: "分享", message: '取消朋友圈分享' });
                            }
                        });
                        //分享给朋友
                        wx.updateAppMessageShareData({
                            desc: _this.getActivity.shareDesc,
                            title: _this.getActivity.shareTitle, // 分享时的标题
                            link: 'https://shanxihongdi.com/hd-api/app/wechatOauth/' + _this.getActivity.id + '?shareId=' + _this.getActivity.userId, // 分享时的链接
                            imgUrl: 'https://shanxihongdi.com/' + _this.getActivity.shareIcon,
                            success: function () {
                                console.log('成功分享给朋友');
                                // this.$Alert({ title: "分享", message: '成功分享给朋友' });
                            },
                            cancel: function () {
                                console.log('已为您取消分享');
                                // this.$Alert({ title: "分享", message: '已为您取消分享' });
                            }
                        });
                    })
                })
        },
        /*
        *  将百度坐标转为GCJ-02(火星坐标):
        */
        transformFromBaiduToGCJ(longitude, latitude) {
            var xPi = 3.14159265358979323846264338327950288 * 3000.0 / 180.0;

            var x = longitude - 0.0065;
            var y = latitude - 0.006;
            var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * xPi);
            var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * xPi);
            var a_latitude = z * Math.sin(theta);
            var a_longitude = z * Math.cos(theta);

            return { longitude: a_longitude, latitude: a_latitude };
        },
        getLocations(val) {
            let _this = this;
            return new Promise(() => {
                wx.checkJsApi({ // 判断当前客户端版本是否支持指定JS接口
                    jsApiList: [
                        'openLocation'
                    ],
                    type: 'gcj02',
                    success: function (res) { // 以键值对的形式返回，可用true，不可用false。如：{"checkResult":{"scanQRCode":true},"errMsg":"checkJsApi:ok"}
                        let point = _this.transformFromBaiduToGCJ(+val.mapX, +val.mapY);
                        console.log('map:', res, {
                            latitude: parseFloat(+val.mapY),
                            longitude: parseFloat(+val.mapX),
                        }, point);
                        wx.openLocation({
                            longitude: parseFloat(+point.longitude),
                            latitude: parseFloat(+point.latitude),
                            name: val.storeName,
                            address: val.address,
                            scale: 15//地图缩放大小，可根据情况具体调整
                        });
                    },
                    fail: function (res) { // 检测getNetworkType该功能失败时处理
                        alert('fail' + res)
                    }
                })
            });
        }
    },
    watch: {
        '$route.path': function (o) {
            this.urlParam = o;
        }
    },
    destroyed() {
        clearInterval(this.timer);
    },
}
